package com.shanghaionstar.vehicle_ownerlife;

import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.EncryptUtil;
import com.onstar.cn.framework.annotation.ContentView;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.mag.PlateEngineNumEntity;
import com.onstar.cn.mag.publicService.response.H5DispatcherResEntity;
import com.onstar.cn.mag.publicService.response.PreferentialResEntity;
import com.onstar.cn.weight.ProgressLayout;
import com.onstar.cn.weight.more.CustomLineLayout;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.webview.handler.CheYinInsuranceHandler;
import com.shanghaionstar.activity.webview.handler.CommonWebViewActivity;
import com.shanghaionstar.activity.webview.handler.IWebType;
import com.shanghaionstar.activity.webview.handler.WebDataEntity;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.home.util.PreferentialResFactory;
import com.shanghaionstar.swipe.SwipeActivity;
import com.shanghaionstar.user.iview.IVehicleInfoView;
import com.shanghaionstar.utils.BannerUtil;
import com.shanghaionstar.utils.BusinessUtil;

import java.util.Locale;

import rx.Subscription;
import rx.functions.Action1;
import rx.subscriptions.Subscriptions;

/**
 * 车检页面：
 * 查看建议车检日期，
 * 车检提醒，
 * 以及预约年检
 * <p/>
 * Created by Yonglang Hong on 2017/1/5.
 */
@ContentView(R.layout.activity_vehicle_inspection)
public class VehicleInspectionActivity extends SwipeActivity {

    /**
     * 行驶证日期
     */
    @FindViewById(R.id.cll_drivingLicenseDate)
    private CustomLineLayout cll_drivingLicenseDate;

    /**
     * 建议预约日期
     */
    @FindViewById(R.id.cll_inspectVehicleDate)
    private CustomLineLayout cll_inspectVehicleDate;

    /**
     * 展开箭头
     */
    @FindViewById(R.id.img_arrow)
    private ImageView img_arrow;

    /**
     * 免责声明
     */
    @FindViewById(R.id.webView)
    private WebView webView;

    /**
     * 免责条款
     */
    @FindViewById(R.id.ll_exceptions)
    private LinearLayout ll_exceptions;

    @FindViewById(R.id.pl_loading)
    private ProgressLayout pl_loading;

    //车主首页传值
    private PreferentialResEntity entity;

    /**
     * 车辆信息获取和设置
     */
    private VehicleInspectionManager inspectionManager;

    public VehicleInspectionManager getVehicleInspectionManager() {
        if (inspectionManager == null) {
            inspectionManager = new VehicleInspectionManager(this);
            inspectionManager.setView(new IVehicleInfoView() {
                @Override
                public void setLoading(boolean isLoading) {
                    pl_loading.setVisibility(isLoading ? View.VISIBLE:View.GONE);
                }
                @Override
                public void onResponseError(OnStarException e) {}
                @Override
                public void onReponseSuccess(PlateEngineNumEntity object) {
                   if (object != null){
                       setLicenseAndInspectDate(object.getDrivingLicenseDate());
                   }
                }
                @Override
                public Activity onActivity() {
                    return VehicleInspectionActivity.this;
                }
            });
        }
        return inspectionManager;
    }

    /**
     * 设置驾驶证日期
     * @param drivingLicenseDate
     */
    private void updateDrivingLicenseDate(String drivingLicenseDate){
        getVehicleInspectionManager().updateDrivingLicenseDate(drivingLicenseDate);
    }
    /**
     * 获取驾驶证日期
     */
    private void getDrivingLicenseDate(){
        getVehicleInspectionManager().getDrivingLicenseDate();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    private void init() {
        if (getIntent() != null) {
            entity = (PreferentialResEntity) getIntent().getSerializableExtra("entity");
            entity = PreferentialResFactory.createVehicleInspectionEntity(entity,this);
        }
        webView.loadUrl(Constants.CURRENT_PREFIX_H5_URL + Constants.INSPECTION_DISCLAIMER_SUFFIX);
        getDrivingLicenseDate();
    }

    /**
     * 设置行驶证日期和预期车检日期
     */
    private void setLicenseAndInspectDate(String licenseDate){
        cll_drivingLicenseDate.setRightText(licenseDate);
        InspectHelper.setLicenseInspectDateAndAlarm(this,licenseDate);
        cll_inspectVehicleDate.setRightText(InspectHelper.getInspectDate(this));
    }

    @OnClick({R.id.cll_drivingLicenseDate, R.id.rcb_subscribeCheck, R.id.img_arrow, R.id.tv_pageTip})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cll_drivingLicenseDate:
                chooseBuyVehicleDateAndGetInspectDate();
                break;
            case R.id.rcb_subscribeCheck:
                subAnnuallyCheck();
                break;
            case R.id.img_arrow:
            case R.id.tv_pageTip:
                toggleDisclaimer();
                break;
        }
    }

    private void toggleDisclaimer() {
        float from = 0f, to = 180f;
        if (ll_exceptions.getVisibility() != View.VISIBLE) {
            ll_exceptions.setVisibility(View.VISIBLE);
            from = 0f;
            to = 180f;
            BusinessUtil.sendReportByClickType(this, FunctionNameFindId.Inspection_OpenDiscalimer.getStringValue());
        } else {
            ll_exceptions.setVisibility(View.GONE);
            from = 180f;
            to = 0f;
            BusinessUtil.sendReportByClickType(this, FunctionNameFindId.Inspection_CloseDiscalimer.getStringValue());
        }
        ObjectAnimator anim = ObjectAnimator.ofFloat(img_arrow, "rotation", from, to);
        anim.setDuration(400);
        anim.start();
    }

    /**
     * 跳转H5web年检预约页面
     */
    private void subAnnuallyCheck() {
//        getH5(entity);
//        Intent intent2 = new Intent(this, CheYinWebActivity.class);
//        intent2.putExtra("url", CheYinWebActivity.INSPECTION_URL);
//        startActivity(intent2);
        BusinessUtil.sendReportByClickType(this, FunctionNameFindId.Inspection_Reservation.getStringValue());
        Intent intent2 = new Intent(this, CommonWebViewActivity.class);
        Bundle bundle = new Bundle();
        WebDataEntity mWebData = new WebDataEntity();
        mWebData.what = IWebType.TYPE_CHE_YIN_INSURANCE;
        mWebData.setTopTitle(getString(R.string.subscribe_yearly_check));
        mWebData.setClzName(CheYinInsuranceHandler.class.getName());
        bundle.putSerializable(IWebType.KEY_SERIAL_DATA,entity);
        bundle.putParcelable(IWebType.KEY_WEB_DATA,mWebData);
        intent2.putExtras(bundle);
//        intent2.putExtra(OnstarWebViewActivity.WEBVIEWS_PROXY_NAME, CheYinInsuranceWebViewProxy.class);
//        intent2.putExtra(CheYinInsuranceWebViewProxy.ENTITY, entity);
        startActivity(intent2);

    }

    protected Subscription subscription = Subscriptions.empty();

    public void getH5(final PreferentialResEntity entity) {
        BannerUtil bannerUtil = new BannerUtil(this);
        subscription = bannerUtil.h5Dispatcher(entity).subscribeOn(getScheduler().backgroundThread())
                .observeOn(getScheduler().mainThread()).subscribe(new Action1<H5DispatcherResEntity>() {
                    @Override
                    public void call(H5DispatcherResEntity mResult) {
                        String url = mResult.getUrl();
                        String body = mResult.getJsonStr();
                        if (!TextUtils.isEmpty(url) && !TextUtils.isEmpty(body))
                            launchCheYin(url, body);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //抛出Error异常
                    }
                });
    }

    /**
     * 车音网调用
     *
     * @param url
     */
    public void launchCheYin(String url, String body) {
        Intent intent2 = new Intent(this, CommonWebViewActivity.class);
        Bundle bundle = new Bundle();
        WebDataEntity mWebData = new WebDataEntity();
        mWebData.setLinkUrl(url);
        mWebData.setClzName(CheYinInsuranceHandler.class.getName());
        bundle.putParcelable(IWebType.KEY_WEB_DATA,mWebData);
        bundle.putString(CheYinInsuranceHandler.PARAM_BODY,body);
//        HashMap<String, String> webViewParam = new HashMap<>();
//        webViewParam.put(OnstarWebViewActivity.URL, url);
//        webViewParam.put(CheYinInsuranceWebViewProxy.PARAM_BODY, body);
//
//        intent2.putExtra(OnstarWebViewActivity.WEBVIEWS_PROXY_NAME, CheYinInsuranceWebViewProxy.class);
//        intent2.putExtra(OnstarWebViewActivity.WEBVIEWS_MAP,webViewParam);
        intent2.putExtras(bundle);
        startActivity(intent2);
    }

    /**
     * 选定购车日期，计算建议车检日期
     */
    private void chooseBuyVehicleDateAndGetInspectDate() {
        BusinessUtil.sendReportByClickType(this, FunctionNameFindId.Inspection_VehicleLicense.getStringValue());
        DateHelper.setDate(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                StringBuilder sb = new StringBuilder();
                sb.append(String.format(Locale.getDefault(), "%d-%02d-%02d",
                        year,
                        monthOfYear + 1,
                        dayOfMonth));
                String licenseDay = sb.toString();
                //设置购买日期
                cll_drivingLicenseDate.setRightText(licenseDay);
                //购车时间在当前日期之后
//                if (DateHelper.nowIsBefore(buyDate)) {
//                    sb.append(String.format(Locale.getDefault(), "%d-%02d-%02d",
//                            year + 2,
//                            monthOfYear + 1,
//                            dayOfMonth));
//                } else {
//                    //购买日期在六年之内，建议每两年年检一次
//                    if (DateHelper.isDateInScope(buyDate, 6)) {
//                        sb.append(String.format(Locale.getDefault(), "%d-%02d-%02d",
//                                year + 2,
//                                monthOfYear + 1,
//                                dayOfMonth));
//                        //若是日期在当前日期之前
//                        sb = formatDate(sb, year + 2, monthOfYear, dayOfMonth, 2);
//                    } else { //从第六年开始则建议每年年检一次
//                        sb.append(String.format(Locale.getDefault(), "%d-%02d-%02d",
//                                year + 1,
//                                monthOfYear + 1,
//                                dayOfMonth));
//                        //若是日期在当前日期之前
//                        sb = formatDate(sb, year + 1, monthOfYear, dayOfMonth, 1);
//                    }
//                }
                //保存年检日期和行驶证日期以及闹钟
                InspectHelper.setLicenseInspectDateAndAlarm(VehicleInspectionActivity.this, licenseDay);
                //设置建议年检日期
                cll_inspectVehicleDate.setRightText(InspectHelper.getInspectDate(VehicleInspectionActivity.this));
                //将驾驶证日期存放后台
                updateDrivingLicenseDate(licenseDay);
            }
        });
    }

    private StringBuilder formatDate(StringBuilder sb, int year, int monthOfYear, int dayOfMonth, int offSet) {
        Log.d("formatDate", sb.toString());
        if (DateHelper.nowIsBefore(sb.toString())) {   //日期
            return sb;
        } else {
            sb = new StringBuilder();
            sb.append(String.format(Locale.getDefault(), "%d-%02d-%02d",
                    year + offSet,
                    monthOfYear + 1,
                    dayOfMonth));
            return formatDate(sb, year + offSet, monthOfYear, dayOfMonth, offSet);
        }
    }

    @Override
    public BasePresenter getPresenter() {
        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (subscription != null && subscription.isUnsubscribed()) {
            subscription.unsubscribe();
        }
        BusinessUtil.sendReportByClickType(this, FunctionNameFindId.Inspection_back.getStringValue());
    }
}
